// import { loadRegionMapConfig } from './config.js';

// 统一地图接口
 export class MapAdapter {
  constructor(mapInstance) {
     this.map = mapInstance;
    //  this.config=config
    //  this.theme = config.get('content.Region', 'light')
    //  console.log("🚀 ~ MapAdapter.js:9 ~ MapAdapter ~ constructor ~  this.theme:",  this.theme)
     }
  addMarker(lng, lat, title) {
    throw new Error('子类必须实现 addMarker',lng, lat, title);
  }
  panTo(lng, lat) {
    throw new Error('子类必须实现 panTo',lng, lat);
  }
  getZoom() {
    throw new Error('子类必须实现 getZoom');
  }
}

// 天地图适配
class TdtAdapter extends MapAdapter {
  addMarker(lng, lat, title) {
    const point = new window.T.LngLat(lng, lat);
    const marker = new window.T.Marker(point);
    this.map.addOverLay(marker);

    if (title) {
      // 创建 Label 覆盖物
      const label = new window.T.Label({
        text: title,
        position: point,
        offset: new window.T.Point(10, -20) // 偏移量，避免遮挡标记
      });
      this.map.addOverLay(label);
    }
  }

  panTo(lng, lat) {
    this.map.panTo(new window.T.LngLat(lng, lat));
  }

  getZoom() {
    return this.map.getZoom();
  }
}

// 百度地图适配
class BdAdapter extends MapAdapter {
  addMarker(lng, lat, title) {
    const point = new window.BMap.Point(lng, lat);
    const marker = new window.BMap.Marker(point);
    this.map.addOverlay(marker);
    if (title) marker.setLabel(new window.BMap.Label(title, { offset: new window.BMap.Size(20, -10) }));
  }
  panTo(lng, lat) { this.map.panTo(new window.BMap.Point(lng, lat)); }
  getZoom()       { return this.map.getZoom(); }
}

// 工厂：根据地区返回对应适配器实例
export async function createMapAdapter(regionCode, domId,config) {
   console.log("🚀 ~ MapAdapter.js:45 ~ createMapAdapter ~ regionCode:", domId)

   const cfg = config.get('content.Region.Regions', { "nanShan": "tdt", "haiTang": "bd" })
  // const cfg = await loadRegionMapConfig(); // {"nanShan":"tdt","haiTang":"bd"}
  const type = cfg[regionCode];
  if (!type) throw new Error(`地区 ${regionCode} 未配置地图类型`);

  // 动态加载 SDK
  if (type === 'tdt') {
    await loadScript('https://api.tianditu.gov.cn/api?v=4.0&tk='+process.env.VUE_APP_TDT_KEY);
    const map = new window.T.Map(domId);
    map.centerAndZoom(new window.T.LngLat(113.93687, 22.52828), 15);
    return new TdtAdapter(map);
  }
  if (type === 'bd') {
    await loadScript('https://api.map.baidu.com/api?v=3.0&ak='+process.env.VUE_APP_BAIDU_KEY);
    const map = new window.BMap.Map(domId);
    map.centerAndZoom(new window.BMap.Point(109.733755, 18.321478), 15);
    return new BdAdapter(map);
  }
  throw new Error(`不支持的地图类型 ${type}`);
}

// 工具：动态插入 <script>
function loadScript(src) {
  return new Promise((resolve, reject) => {
    if (document.querySelector(`script[src="${src}"]`)) return resolve();
    const s = document.createElement('script');
    s.src = src;
    s.onload = resolve;
    s.onerror = reject;
    document.head.appendChild(s);
  });
}